/**
 * Created by sxwu on 14-2-14.
 */
/*登陆*/

var log = require("../lib/log");
var config = require('../config');
var User = require('../models/viruser');
var crypto = require('crypto');
var RUtil = require('./dataformatUtil');
var roles = require('../models/roles');

exports.login = function(request, response) {
    var method = request.method || '';
    var data = RUtil.front_data(request);
    data.title = '管理员登录';
    data.uname = '';
    var resdata = RUtil.retdata(request);
    // 登录页面
    if(method.toUpperCase() === "GET") {
        response.render('login', data);
    }

    // 登录验证请求
    else if(method.toUpperCase() === "POST") {
        var uname = request.body.uname;
        data.uname = uname;
        if(request.body.uname=="" || request.body.passwd=="")
        {
            resdata.info = "登录失败：账户名或密码为空！";
            response.send(resdata);
            return;
        }
        else
        {
            User.selectForLogin(uname, function(error,results) {
                //log.info("用户信息：" + require('util').inspect(results));
                if((error)!== null)
                {
                    // 数据库异常
                    resdata.info = "登录失败：系统内部错误(错误码："+error.errno+")";
                    resdata.retType="alert-error";
                    response.send(resdata);
                    return;
                }
                else if(results.length <= 0) {
                    // 用户不存在
                    resdata.info =  "登录失败：账户不存在或未激活！";
                    resdata.retType="alert-error";
                    response.send(resdata);
                    return;
                }
                else
                {
                    var tmpUser = results[0];
                    var passwd = request.body.passwd;
                    if(tmpUser.userflag!==1)
                    {
                        resdata.info="登录失败：未激活，请联系系统管理员激活！";
                        resdata.retType="alert-error";
                        response.send(resdata);
                        return;
                    }
                    var curdate = new Date(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate());
                    var arr = tmpUser.expiredate.split("-");
                    var expdate = new Date(arr[0], arr[1], arr[2]);

                    if(expdate < curdate)
                    {
                        resdata.info="登录失败：账户已过期，请联系系统管理员激活！";
                        resdata.retType="alert-error";
                        response.send(resdata);
                        return;
                    }
                    passwd = crypto.createHash('md5').update(passwd).digest('hex');
                    if( tmpUser.userpwd.toLowerCase() === passwd.toLowerCase()) {
                        // 登录成功
                        roles.selectByID(tmpUser.roleid, function(error,results){
                            if((error)!== null)
                            {
                                // 数据库异常
                                resdata.info = "登录失败：系统内部错误(错误码："+error.errno+")";
                                resdata.retType="alert-error";
                                response.send(resdata);
                                return;
                            }
                            else if(results.length <= 0) {
                                // 不存在
                                resdata.info = "登录失败：账户权限不合法！";
                                resdata.retType="alert-error";
                                response.send(resdata);
                                return;
                            }
                            else
                            {
                                request.session.roleinfo=results[0];
                                request.session.admin = tmpUser;
                                RUtil.writeoperlog(request,'登录','登录平台成功');

                                User.updateLoginInfo({lastloginip:RUtil.getClientIp(request),id:request.session.admin.id}, function(error,results){});

                                resdata.success=true;
                                resdata.info="登录成功";
                                resdata.url=request.session.lastpage || "/index.html";
                                response.send(resdata);

                                return;
                            }
                        });


                    }
                    else
                    {
                        request.session.admin = tmpUser;
                        RUtil.writeoperlog(request,'登录','登录失败：密码错误');
                        request.session.admin = null;
                        resdata.info="登录失败：账户名或密码错误！";
                        resdata.retType="alert-error";
                        response.send(resdata);
                        return;

                    }
                };

            });
        }
    }

    };
/**
 * 登出系统
 */
exports.logout = function(request, response) {
    RUtil.writeoperlog(request,'登录','退出平台');
    request.session.admin = null;
    request.session.roleinfo=null;
    response.redirect("/login.html");
};

/**
 * 检查是否登陆
 * @param request
 * @param response
 */
exports.checklogin=function(request, response) {
    if(request.session.admin==undefined)
    {
        response.redirect("login.html");
    }
}